/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.cardarus.operatingsystem.struts.actions;

import com.cardarus.operatingsystem.domain.Customer;
import com.cardarus.operatingsystem.domain.SalesTransaction;
import com.cardarus.operatingsystem.model.BusinessModel;
import com.cardarus.operatingsystem.struts.forms.CustomerPinForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * Associates a Customer to the current sales transaction, base on the provided PIN
 * This action is called from the Struts framework.
 * 
 * @author Javier Snaider
 */
public class CustomerPinAction extends org.apache.struts.action.Action {
    
    /**
     * This action is called from the Struts framework.
     *
     *Associates a Customer to the current sales transaction, base on the
     * provided PIN.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionErrors errors = new ActionErrors();
        CustomerPinForm cform = (CustomerPinForm)form;
        BusinessModel model = BusinessModel.getInstance();
        HttpSession session = request.getSession();

        Customer customer = model.getCustomerByPin(cform.getPin());
        if (customer != null){
            session.setAttribute("customer", customer);
            SalesTransaction sale = (SalesTransaction) session.getAttribute("sale");
            if(sale != null){
            sale.setCustomer(customer);
            }
        }else{
            session.removeAttribute("customer");
            errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("checkout.invalidPin"));
        }
        return mapping.findForward("success");
    }
}
